package com.qymerge.manage.base.service.impl;

import com.qymerge.manage.base.dao.*;
import com.qymerge.manage.base.ro.*;
import com.qymerge.manage.base.service.IMetaBudgetProductService;
import com.qymerge.manage.core.bean.ActionResultRO;
import com.qymerge.manage.core.bean.DataTableRO;
import com.qymerge.manage.core.bean.PageRequest;
import com.qymerge.manage.core.utils.ReadExcelBudgetUtil;
import com.qymerge.manage.core.utils.ReadExcelUtil;
import com.qymerge.manage.data.ro.YyueRO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: MetaProfitReportItemServiceImpl</p>
 * <p>Description: 利润表报表项目配置</p>
 *
 * @author Xiao
 * @date 2025/4/29 18:43
 * @version 1.0.0
 */
@Service
public class MetaBudgetProductServiceImpl implements IMetaBudgetProductService {

    @Autowired
    private IMetaBudgetProductDao metaBudgetProductDao;
    @Autowired
    private IMetaBudgetDao metaBudgetDao;
    @Autowired
    private IMetaMaterialDao metaMaterialDao;
    @Autowired
    private IMetaCompanyDao metaCompanyDao;
    @Autowired
    private IMetaPeriodDao metaPeriodDao;

    /**
     * 查询
     *
     * @param ro
     * @param pageRequest
     * @return
     */
    @Override
    public DataTableRO list(MetaBudgetProductRO ro, PageRequest pageRequest) {
        List<MetaBudgetProductRO> list = metaBudgetProductDao.list(ro, pageRequest);
        DataTableRO dataTableRO = new DataTableRO();
        int allCount = metaBudgetProductDao.total(ro);
        int pageSize = pageRequest.getSize();
        dataTableRO.setAll_count(allCount);
        dataTableRO.setList(list);
        dataTableRO.setCurrent_page(pageRequest.getPage());
        dataTableRO.setPage_size(pageSize);
        int allPage = (allCount % pageSize == 0 ? allCount / pageSize : allCount / pageSize + 1);
        dataTableRO.setAll_page(allPage);
        return dataTableRO;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public MetaBudgetProductRO detail(Long id) {
        MetaBudgetProductRO profitReportItemDaoOne = metaBudgetProductDao.findOne(id);
        return profitReportItemDaoOne;
    }

    /**
     *
     * @param ro
     * @return
     */
    @Override
    public ActionResultRO save(MetaBudgetProductRO ro) {
        // 获取主表信息
        MetaBudgetRO budgetRO = metaBudgetDao.findOne(ro.getBudgetId());
        if (budgetRO != null) {
            ro.setInternalCompanyId(budgetRO.getInternalCompanyId());    // 关联公司
            ro.setPeriodYear(budgetRO.getPeriodYear());
        }
        int rn = 0;
        MetaBudgetProductRO searchMetaBudgetProductRO = metaBudgetProductDao.findOneByYearMonthCode(ro.getBudgetId(), ro.getPeriodYear(),ro.getPeriodMonth(), ro.getMaterialCode());
        if (ro.getId() == 0 && searchMetaBudgetProductRO == null) {
            rn = metaBudgetProductDao.insert(ro);
        } else {
            ro.setId(searchMetaBudgetProductRO.getId());
            rn = metaBudgetProductDao.update(ro);
        }
        return new ActionResultRO(rn, ro.getId() == 0 ? "保存成功" : "修改成功", ro.getId() == 0 ? "保存失败" : "修改失败");
    }

    @Override
    public ActionResultRO delete(Long[] ids) {
        int rn = metaBudgetProductDao.remove(Arrays.asList(ids));
        return new ActionResultRO(true, "删除" + rn +"成功", "删除" + rn +"失败");
    }

    @Override
    public ActionResultRO importData(MultipartFile multipartFile, Long BudgetId) {
        StringBuffer tip = new StringBuffer("导入结果：<br/>");
        ReadExcelUtil readExcelUtil = new ReadExcelUtil();
        List<String[][]> datas = null;
        try {
            datas = readExcelUtil.readByStream(multipartFile.getInputStream(), 2, multipartFile.getOriginalFilename());
            if (org.springframework.util.CollectionUtils.isEmpty(datas)) {
                return new ActionResultRO(false, "execl数据为空");
            }
            String[][] data = datas.get(0);

            Long budgetId= BudgetId;
            String internalCompanyId = "";

            //String periodId = "";
            Integer periodYear= 0;
            Integer periodMonth= 0;

            String materialId= "";
            String materialName= "";
            String materialCode= "";

            Integer packQuantity = 0;
            Integer stdPackQuantity = 0;

            BigDecimal revenueAmount = BigDecimal.ZERO;
            BigDecimal costAmount = BigDecimal.ZERO;

            List<MetaBudgetProductRO> roNewList = new ArrayList<>();
            MetaBudgetProductRO ro = null;
            int rowNum = 1;        // 记录当前行
            int successNum = 0;    // 记录新增或者更新记录数
            for (String[] row : data) {
                rowNum++;

                //budgetId = Long.valueOf(row[0]);
                internalCompanyId = row[0];
                periodYear = Integer.valueOf(row[1]);
                periodMonth = Integer.valueOf(row[2]);
                materialId= row[3];
                materialName= row[4];
                materialCode= row[5];
                packQuantity= Integer.valueOf(row[6]);
                stdPackQuantity= Integer.valueOf(row[7]);
                revenueAmount= BigDecimal.valueOf(Double.valueOf(row[8]));
                costAmount= BigDecimal.valueOf(Double.valueOf(row[9]));

                if (StringUtils.isEmpty(budgetId + "")
                        || StringUtils.isEmpty(internalCompanyId)
                        || StringUtils.isEmpty(materialId)
                        || StringUtils.isEmpty(revenueAmount+"")
                        || StringUtils.isEmpty(costAmount+"")
                ) {
                    tip.append("第").append(rowNum).append("行：部分数据为空，不予新增<br/>");
                    continue;
                }
                MetaCompanyRO companyRO = metaCompanyDao.findOne(internalCompanyId);
                if (companyRO == null) {
                    tip.append("第").append(rowNum).append("行：关联公司不存在，不予新增<br/>");
                    continue;
                }
//                MetaPeriodRO periodRO = metaPeriodDao.findOne(periodId);
//                if (periodRO == null) {
//                    tip.append("第").append(rowNum).append("行：关联会计期间不存在，不予新增<br/>");
//                    continue;
//                }
                MetaMaterialRO materialRO = metaMaterialDao.findOne(materialId);
                if (materialRO == null) {
                    tip.append("第").append(rowNum).append("行：关联物料不存在，不予新增<br/>");
                    continue;
                }

                ro = new MetaBudgetProductRO(budgetId, internalCompanyId, periodYear, periodMonth, materialId, materialName, materialCode, packQuantity,stdPackQuantity,revenueAmount,costAmount);
                roNewList.add(ro);
            }

            if (tip.toString().equals("导入结果：<br/>")) {
                for (MetaBudgetProductRO metaBudgetProductRO : roNewList) {
                    metaBudgetProductDao.insert(ro);
                    successNum++;
                }

                tip.append("成功新增记录：").append(successNum).append("条");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new ActionResultRO(false, "导入失败");
        }

        return new ActionResultRO(true, tip.toString());
    }

    @Override
    public ActionResultRO importData2(MultipartFile multipartFile, Long BudgetId) {
        StringBuffer tip1 = new StringBuffer("导入结果-销量:<br/>");
        StringBuffer tip2 = new StringBuffer("导入结果-主营业务收入:<br/>");
        StringBuffer tip3 = new StringBuffer("导入结果-主营业务成本:<br/>");
        ReadExcelBudgetUtil readExcelUtil = new ReadExcelBudgetUtil();
        Map<String, String[][]> datas = null;
        try {
            datas = readExcelUtil.readByStream(multipartFile.getInputStream(), 5, 3, multipartFile.getOriginalFilename());
            if (org.springframework.util.CollectionUtils.isEmpty(datas)) {
                return new ActionResultRO(false, "execl数据为空");
            }
            String[][] sales_datas = datas.get("sales_datas");      // 销量
            String[][] income_datas = datas.get("income_datas");    // 收入
            String[][] cost_datas = datas.get("cost_datas");        // 成本

            Long budgetId= BudgetId;
            String internalCompanyId = "";

            //String periodId = "";
            Integer periodYear= 0;
            Integer periodMonth= 0;

            String materialId= "";
            String materialName= "";
            String materialCode= "";

            Integer packQuantity = 0;
            Integer stdPackQuantity = 0;

            BigDecimal revenueAmount = BigDecimal.ZERO;
            BigDecimal costAmount = BigDecimal.ZERO;

            List<MetaBudgetProductRO> roNewList1 = new ArrayList<>();
            List<MetaBudgetProductRO> roNewList2 = new ArrayList<>();
            List<MetaBudgetProductRO> roNewList3 = new ArrayList<>();

            int rowNum1 = 5;        // 记录当前行
            int rowNum2 = 5;        // 记录当前行
            int rowNum3 = 5;        // 记录当前行
            int successNum1 = 0;     // 记录新增或者更新记录数
            int successNum11 = 0;     // 记录新增或者更新记录数
            int successNum2 = 0;     // 记录新增或者更新记录数
            int successNum22 = 0;     // 记录新增或者更新记录数
            int successNum3 = 0;     // 记录新增或者更新记录数
            int successNum33 = 0;     // 记录新增或者更新记录数

            // 获取主表信息
            MetaBudgetRO budgetRO = metaBudgetDao.findOne(BudgetId);
            if (budgetRO != null) {
                internalCompanyId = budgetRO.getInternalCompanyId();    // 关联公司
                periodYear = budgetRO.getPeriodYear();          // 年
            }

            // 销量添加个更新
            if (ArrayUtils.isNotEmpty(sales_datas)) {

                for (int k = 0; k < sales_datas.length; k++) {
                    String[] row = sales_datas[k];

                    // budgetId = Long.valueOf(row[0]);
                    materialCode= row[0];
                    materialName= row[1];

                    MetaMaterialRO materialRO = metaMaterialDao.findOneByCode(materialCode);
                    if (materialRO == null) {
                        tip1.append("第").append(rowNum1).append("行：关联产品编码不存在，不予新增 <br/>");
                        continue;
                    } else {
                        materialId = materialRO.getId();                    // 设置物料Id
                        stdPackQuantity = materialRO.getQtyPerStdPack();    // 标准箱
                    }

                    int j = 2;
                    // 同一个产品增加12条数据
                    for (int i = 1; i <= 12; i++) {
                        if (StringUtils.isNotBlank(row[j])) {
                            packQuantity = Integer.valueOf(row[j]);
                        } else{
                            packQuantity = 0;
                        }
                        MetaBudgetProductRO ro = new MetaBudgetProductRO(budgetId, internalCompanyId, periodYear, i, materialId, materialName, materialCode, packQuantity, stdPackQuantity, revenueAmount, costAmount);
                        roNewList1.add(ro);

                        j = j+1;
                    }

                    rowNum1++;
                }


            }
            if (ArrayUtils.isNotEmpty(income_datas)) {
                for (int k = 0; k < income_datas.length; k++) {
                    String[] row = income_datas[k];

                    // budgetId = Long.valueOf(row[0]);
                    materialCode = row[0];
                    materialName = row[1];

                    MetaMaterialRO materialRO = metaMaterialDao.findOneByCode(materialCode);
                    if (materialRO == null) {
                        tip2.append("第").append(rowNum2).append("行：关联产品编码不存在，不予新增<br/> ");
                        continue;
                    } else {
                        materialId = materialRO.getId();                    // 设置物料Id
                        stdPackQuantity = materialRO.getQtyPerStdPack();    // 标准箱
                    }

                    int j = 2;
                    // 同一个产品增加12条数据
                    for (int i = 1; i <= 12; i++) {
                        if (StringUtils.isNotBlank(row[j])) {
                            revenueAmount = BigDecimal.valueOf(Double.valueOf(row[j]));
                        } else {
                            revenueAmount = BigDecimal.ZERO;
                        }
                        MetaBudgetProductRO ro = new MetaBudgetProductRO(budgetId, internalCompanyId, periodYear, i, materialId, materialName, materialCode, packQuantity, stdPackQuantity, revenueAmount, costAmount);
                        roNewList2.add(ro);

                        j = j + 1;
                    }

                    rowNum2++;
                }

            }
            if (ArrayUtils.isNotEmpty(cost_datas)) {
                for (int k = 0; k < cost_datas.length; k++) {
                    String[] row = cost_datas[k];

                    // budgetId = Long.valueOf(row[0]);
                    materialCode = row[0];
                    materialName = row[1];

                    MetaMaterialRO materialRO = metaMaterialDao.findOneByCode(materialCode);
                    if (materialRO == null) {
                        tip3.append("第").append(rowNum3).append("行：关联产品编码不存在，不予新增 <br/>");
                        continue;
                    } else {
                        materialId = materialRO.getId();                    // 设置物料Id
                        stdPackQuantity = materialRO.getQtyPerStdPack();    // 标准箱
                    }

                    int j = 2;
                    // 同一个产品增加12条数据
                    for (int i = 1; i <= 12; i++) {
                        if (StringUtils.isNotBlank(row[j])) {
                            costAmount = BigDecimal.valueOf(Double.valueOf(row[j]));
                        } else {
                            costAmount = BigDecimal.ZERO;
                        }
                        MetaBudgetProductRO ro = new MetaBudgetProductRO(budgetId, internalCompanyId, periodYear, i, materialId, materialName, materialCode, packQuantity, stdPackQuantity, revenueAmount, costAmount);
                        roNewList3.add(ro);

                        j = j + 1;
                    }

                    rowNum3++;
                }
            }

            // 统一处理执行操作，一个sheet有问题，整个表格不做执行处理
            if (tip1.toString().equals("导入结果-销量:<br/>") &&
                    tip2.toString().equals("导入结果-主营业务收入:<br/>") &&
                    tip3.toString().equals("导入结果-主营业务成本:<br/>")) {
                for (MetaBudgetProductRO metaBudgetProductRO : roNewList1) {
                    MetaBudgetProductRO searchMetaBudgetProductRO = metaBudgetProductDao.findOneByYearMonthCode(metaBudgetProductRO.getBudgetId(), metaBudgetProductRO.getPeriodYear(),metaBudgetProductRO.getPeriodMonth(), metaBudgetProductRO.getMaterialCode());
                    if (searchMetaBudgetProductRO != null) {
                        metaBudgetProductRO.setBudgetId(searchMetaBudgetProductRO.getBudgetId());
                        metaBudgetProductDao.updatePackQuantity(metaBudgetProductRO);
                        successNum11++;
                    } else {
                        metaBudgetProductDao.insert(metaBudgetProductRO);
                        successNum1++;
                    }
                }
                tip1.append("成功更新记录：").append(successNum11).append("条 <br/>");
                tip1.append("成功新增记录：").append(successNum1).append("条 <br/>");

                for (MetaBudgetProductRO metaBudgetProductRO : roNewList2) {
                    MetaBudgetProductRO searchMetaBudgetProductRO = metaBudgetProductDao.findOneByYearMonthCode(metaBudgetProductRO.getBudgetId(), metaBudgetProductRO.getPeriodYear(),metaBudgetProductRO.getPeriodMonth(), metaBudgetProductRO.getMaterialCode());
                    if (searchMetaBudgetProductRO != null) {
                        metaBudgetProductRO.setId(searchMetaBudgetProductRO.getId());
                        metaBudgetProductDao.updateRevenueAmount(metaBudgetProductRO);
                        successNum22++;
                    } else {
                        metaBudgetProductDao.insert(metaBudgetProductRO);
                        successNum2++;
                    }
                }
                tip2.append("成功更新记录：").append(successNum22).append("条 <br/>");
                tip2.append("成功新增记录：").append(successNum2).append("条 <br/>");

                for (MetaBudgetProductRO metaBudgetProductRO : roNewList3) {
                    MetaBudgetProductRO searchMetaBudgetProductRO = metaBudgetProductDao.findOneByYearMonthCode(metaBudgetProductRO.getBudgetId(), metaBudgetProductRO.getPeriodYear(), metaBudgetProductRO.getPeriodMonth(), metaBudgetProductRO.getMaterialCode());
                    if (searchMetaBudgetProductRO != null) {
                        metaBudgetProductRO.setId(searchMetaBudgetProductRO.getId());
                        metaBudgetProductDao.updateCostAmount(metaBudgetProductRO);
                        successNum33++;
                    } else {
                        metaBudgetProductDao.insert(metaBudgetProductRO);
                        successNum3++;
                    }
                }
                tip3.append("成功更新记录：").append(successNum33).append("条 <br/>");
                tip3.append("成功新增记录：").append(successNum3).append("条 <br/>");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return new ActionResultRO(false, "导入失败");
        }

        return new ActionResultRO(true, tip1.append(tip2).append(tip3).toString());
    }


}
